package yhao.infra.feature.qiniu.oss.core;

import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * @author yoara
 * <p> Created on 2019/3/27 </p>
 */
public class DownloadUtil {

    public static byte[] downloadAttachment(String uri)
            throws IOException {
        HttpResponse httpResponse = doGetHttpResponse(uri);
        return EntityUtils.toByteArray(httpResponse.getEntity());
    }

    /**
     * 下载远程资源
     *
     * @param request
     * @param response
     * @param uri
     * @param filename
     * @throws HttpException
     * @throws IOException
     */
    public static void downloadAttachment(HttpServletRequest request,
                                          HttpServletResponse response, String uri, String filename)
            throws IOException {
        downloadAttachment(request, response, uri, filename, true);
    }

    /**
     * Download the attachment<br>
     * do not forget close the OutputStream after use the method
     *
     * @param request
     * @param response
     * @param uri
     * @param filename
     * @param isCloseOutputStream
     * @throws HttpException
     * @throws IOException
     */
    public static void downloadAttachment(HttpServletRequest request, HttpServletResponse response,
                                          String uri, String filename, boolean isCloseOutputStream) throws IOException {
        //First step: get data by the uri
        HttpResponse httpResponse = doGetHttpResponse(uri);

        InputStream stream = httpResponse.getEntity().getContent();

        downloadAttachment(request, response, stream, filename, isCloseOutputStream);
    }

    private static HttpResponse doGetHttpResponse(String uri) throws IOException {
        HttpClient client = HttpClientBuilder.create().build();
        HttpGet get = new HttpGet(uri);
        return client.execute(get);
    }


    public static void downloadAttachment(HttpServletRequest request,
                                          HttpServletResponse response, InputStream stream, String filename,
                                          boolean isCloseOutputStream)
            throws IOException {
        // Remove blank in the filename, but do not use regex(\s) for some reason
        filename = filename.replace(" ", "");

        // get client agent info，and encode the filename.(only in IE、FF、Chrome)
        String agent = request.getHeader("USER-AGENT");
        if (agent != null && agent.toUpperCase().indexOf("MSIE") != -1) { // IE
            filename = URLEncoder.encode(filename, "UTF-8");
        } else {    // Other
            filename = new String(filename.getBytes(), "ISO-8859-1");
        }

        // output the data to client
        response.reset();
        response.addHeader("Content-Disposition", "attachment;filename=" + filename);
        response.setContentType("application/octet-stream; charset=UTF-8");
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            byte b[] = new byte[1024];
            int j = 0;
            while ((j = stream.read(b)) != -1) {
                out.write(b, 0, j);
            }
            out.flush();
        } finally {
            if (isCloseOutputStream && out != null) {
                out.close();
            }
        }
    }

}
